// --- DOM Element References ---
const versionAInput = document.getElementById('version_a');
const versionBInput = document.getElementById('version_b');
const platformSelect = document.getElementById('platform');
const maxreaderInput = document.getElementById('max_reader');
const predictButton = document.getElementById('predict_button');
const loadingIndicator = document.getElementById('loading_indicator');
const resultsSection = document.getElementById('results-section');
const danmakuContainer = document.getElementById('danmaku_container');

// 结果元素引用
const likeResultEl = document.querySelector('.confidence-badge');
const likeAEl = document.querySelector('.values .version-a');
const likeBEl = document.querySelector('.values .version-b');
const commentResultEl = document.querySelectorAll('.confidence-badge')[1];
const commentAEl = document.querySelectorAll('.values .version-a')[1];
const commentBEl = document.querySelectorAll('.values .version-b')[1];
const shareResultEl = document.querySelectorAll('.confidence-badge')[2];
const shareAEl = document.querySelectorAll('.values .version-a')[2];
const shareBEl = document.querySelectorAll('.values .version-b')[2];
const favResultEl = document.querySelectorAll('.confidence-badge')[3];
const favAEl = document.querySelectorAll('.values .version-a')[3];
const favBEl = document.querySelectorAll('.values .version-b')[3];
const currentReaderEl = document.getElementById('current_reader');

// 按钮引用
const clearBtn = document.getElementById('clear-btn');
const saveBtn = document.getElementById('save-btn');
const uploadBtn = document.getElementById('upload-btn');
const exportBtn = document.querySelector('.result-actions .btn-outline');
const shareBtn = document.querySelectorAll('.result-actions .btn-outline')[1];
const startTestBtn = document.querySelector('.hero-buttons .btn-primary');
const learnMoreBtn = document.querySelector('.hero-buttons .btn-outline');

// Chart elements
const engagementChartCanvas = document.getElementById('engagement_chart');
let engagementChart; // To hold the Chart.js instance
let eventSource = null; // To hold the EventSource instance

// --- Chart Initialization ---
function initializeChart() {
    const ctx = engagementChartCanvas.getContext('2d');
    if (engagementChart) {
        engagementChart.destroy();
    }
    engagementChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['0', '1', '2', '3', '4'], // 初始模拟步数
            datasets: [
                {
                    label: '版本 A 互动',
                    data: [12, 35, 98, 165, 782], // 初始模拟数据
                    borderColor: 'var(--color-primary-500)',
                    backgroundColor: 'rgba(59, 130, 246, 0.5)',
                    tension: 0.1
                },
                {
                    label: '版本 B 互动',
                    data: [0, 5, 58, 162, 175], // 初始模拟数据
                    borderColor: 'var(--color-accent-500)',
                    backgroundColor: 'rgba(0, 212, 200, 0.5)',
                    tension: 0.1
                }
            ]
        },
        options: {
            plugins: {
                title: {
                    display: true,
                    text: '曝光量与累计互动数关系（模拟数据）'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: { display: true, text: '累计互动数' }
                },
                x: {
                    title: { display: true, text: '曝光量（万次）' }
                }
            },
            responsive: true,
            maintainAspectRatio: false
        }
    });
}

// --- Initial Setup ---


// --- Update UI Functions ---
function updateCumulativeResults(cumulativeData, confidenceData, readerCount) {
    if (likeAEl) likeAEl.textContent = cumulativeData.like_a;
    if (likeBEl) likeBEl.textContent = cumulativeData.like_b;
    if (likeResultEl) likeResultEl.textContent = `${confidenceData.like.value.toFixed(2)}%`;

    if (commentAEl) commentAEl.textContent = cumulativeData.comment_a;
    if (commentBEl) commentBEl.textContent = cumulativeData.comment_b;
    if (commentResultEl) commentResultEl.textContent = `${confidenceData.comment.value.toFixed(2)}%`;

    // 更新转发和收藏数据
    const shareAEl = document.querySelectorAll('.values .version-a')[2];
    const shareBEl = document.querySelectorAll('.values .version-b')[2];
    const shareResultEl = document.querySelectorAll('.confidence-badge')[2];
    const quoteAEl = document.querySelectorAll('.values .version-a')[3];
    const quoteBEl = document.querySelectorAll('.values .version-b')[3];
    const quoteResultEl = document.querySelectorAll('.confidence-badge')[3];
    
    if (shareAEl) shareAEl.textContent = cumulativeData.share_a;
    if (shareBEl) shareBEl.textContent = cumulativeData.share_b;
    if (shareResultEl) shareResultEl.textContent = `${confidenceData.share.value.toFixed(2)}%`;
    
    if (quoteAEl) quoteAEl.textContent = cumulativeData.quote_a;
    if (quoteBEl) quoteBEl.textContent = cumulativeData.quote_b;
    if (quoteResultEl) quoteResultEl.textContent = `${confidenceData.quote.value.toFixed(2)}%`;

    if (currentReaderEl) currentReaderEl.textContent = readerCount;
    if (resultsSection) resultsSection.style.display = 'block';
}

function updateChart(chartData) {
    if (engagementChart) {
        engagementChart.data.labels = chartData.user_steps;
        engagementChart.data.datasets[0].data = chartData.engagement_a;
        engagementChart.data.datasets[1].data = chartData.engagement_b;
        engagementChart.update();
    }
}

// --- Danmaku Function ---
let danmakuQueue = [];
let isDanmakuPlaying = false;

function playNextDanmaku() {
    if (danmakuQueue.length === 0 || isDanmakuPlaying) return;
    
    isDanmakuPlaying = true;
    const { reader, predictionA, predictionB } = danmakuQueue.shift();
    
    const danmaku = document.createElement('div');
    danmaku.classList.add('danmaku-item');

    let content = `读者 ${reader}: `;
    if (predictionA.like) content += '👍 ';
    if (predictionA.comment) content += '💬 ';
    if (predictionA.share) content += '🔁 ';
    if (predictionB.like) content += '👍 ';
    if (predictionB.comment) content += '💬 ';
    if (predictionB.share) content += '🔁 ';

    danmaku.textContent = content;
    danmakuContainer.appendChild(danmaku);

    // 动画结束后移除
    danmaku.addEventListener('animationend', () => {
        danmaku.remove();
        isDanmakuPlaying = false;
        playNextDanmaku();
    });
}

function addDanmaku(reader, predictionA, predictionB) {
    if (!danmakuContainer) return;
    
    danmakuQueue.push({ reader, predictionA, predictionB });
    
    if (!isDanmakuPlaying) {
        playNextDanmaku();
    }
}

function resetResults() {
    engagementChart.data.labels = [];
    engagementChart.data.datasets[0].data = [];
    engagementChart.data.datasets[1].data = [];
    engagementChart.update();
    
    // Reset all result values to 0
    if (likeAEl) likeAEl.textContent = '0';
    if (likeBEl) likeBEl.textContent = '0';
    if (likeResultEl) likeResultEl.textContent = '0%';
    
    if (commentAEl) commentAEl.textContent = '0';
    if (commentBEl) commentBEl.textContent = '0';
    if (commentResultEl) commentResultEl.textContent = '0%';
    
    if (shareAEl) shareAEl.textContent = '0';
    if (shareBEl) shareBEl.textContent = '0';
    if (shareResultEl) shareResultEl.textContent = '0%';
    
    if (favAEl) favAEl.textContent = '0';
    if (favBEl) favBEl.textContent = '0';
    if (favResultEl) favResultEl.textContent = '0%';
    
    // Keep results section visible
    if (resultsSection) resultsSection.style.display = 'block';
    
    if (currentReaderEl) currentReaderEl.textContent = '0';
    
    if (danmakuContainer) danmakuContainer.innerHTML = '';
    resetResults();
    
    if (engagementChart) {
        engagementChart.data.labels = [];
        engagementChart.data.datasets[0].data = [];
        engagementChart.data.datasets[1].data = [];
        engagementChart.update();
    }
}

// --- 字符计数功能 ---
function updateCharCount() {
    const lengthA = versionAInput.value.length;
    const lengthB = versionBInput.value.length;
    
    document.getElementById('count_a').textContent = lengthA;
    document.getElementById('count_b').textContent = lengthB;
}

versionAInput.addEventListener('input', updateCharCount);
versionBInput.addEventListener('input', updateCharCount);

// --- 按钮事件处理 ---
clearBtn.addEventListener('click', () => {
    versionAInput.value = '';
    versionBInput.value = '';
    updateCharCount();
});

saveBtn.addEventListener('click', () => {
    alert('草稿保存功能将在后续版本实现');
});

uploadBtn.addEventListener('click', () => {
    alert('媒体上传功能将在后续版本实现');
});

exportBtn.addEventListener('click', () => {
    alert('结果导出功能将在后续版本实现');
});

shareBtn.addEventListener('click', () => {
    alert('结果分享功能将在后续版本实现');
});


// --- Event Listener ---
predictButton.addEventListener('click', async () => {
    if (eventSource) {
        eventSource.close();
    }

    const versionA = versionAInput.value.trim();
    const versionB = versionBInput.value.trim();
    const platform = platformSelect.value;
    const maxreader = parseInt(maxreaderInput.value, 10);
    const model = "deepseek-chat";

    if (!versionA || !versionB) {
        alert('请填写所有必填项 (内容 A, 内容 B)。');
        return;
    }
    if (isNaN(maxreader) || maxreader <= 0 || maxreader > 50) {
        alert('最大读者数必须是1-50之间的正整数。');
        return;
    }

    loadingIndicator.style.display = 'block';
    predictButton.disabled = true;
    predictButton.querySelector('.btn-spinner').style.display = 'inline-block';
    predictButton.querySelector('.btn-text').textContent = '分析中...';
    // 重置结果但不重置图表
    engagementChart.data.labels = [];
    engagementChart.data.datasets[0].data = [];
    engagementChart.data.datasets[1].data = [];
    engagementChart.update();
    
    if (resultsSection) resultsSection.style.display = 'block';

    const requestData = {
        version_a: versionA,
        version_b: versionB,
        platform: platform,
        max_reader: maxreader,
        model: "deepseek-chat"
    };

    const baseUrl = 'http://localhost:8000/predict';
    const queryParams = new URLSearchParams(requestData).toString();
    const url = `${baseUrl}?${queryParams}`;

    eventSource = new EventSource(url);

    eventSource.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data);

            switch (data.type) {
                case 'update':
                    handleStreamUpdate(data);
                    break;
                case 'final':
                    handleStreamFinal(data);
                    break;
                case 'done':
                    handleStreamDone();
                    break;
                case 'error':
                    handleStreamError(data);
                    break;
                default:
                    console.warn("Unknown SSE message type:", data.type);
            }
        } catch (error) {
            console.error('Error parsing SSE data:', error);
            handleStreamError({ message: "接收到无效的数据格式。" });
        }
    };

    eventSource.onerror = (error) => {
        console.error('EventSource failed:', error);
        alert('与服务器的实时连接失败。请检查后端服务是否运行，或网络连接。');
        handleStreamDone();
    };
});

// --- SSE Handler Functions ---
function handleStreamUpdate(data) {
    loadingIndicator.style.display = 'none';
    resultsSection.style.display = 'block';
    showPredictingStatus(); // 在这里添加预测状态显示

    addDanmaku(data.reader, data.prediction_a, data.prediction_b);
    updateCumulativeResults(data.cumulative, data.confidence, data.reader);
    updateChart(data.chart_data);
}

function handleStreamFinal(data) {
    updateCumulativeResults(data.cumulative, data.confidence, data.reader);
    updateChart(data.chart_data);
}

function handleStreamDone() {
    console.log("SSE stream finished.");
    if (eventSource) {
        eventSource.close();
        eventSource = null;
    }
    loadingIndicator.style.display = 'none';
    predictButton.disabled = false;
    predictButton.querySelector('.btn-spinner').style.display = 'none';
    predictButton.querySelector('.btn-text').textContent = '比较';
    currentReaderEl.textContent += " (完成)";
}

function handleStreamError(errorData) {
    console.error('SSE Error message:', errorData.message);
    alert(`实时预测出错: ${errorData.message}`);
    handleStreamDone();
}

// --- Initial Setup ---
document.addEventListener('DOMContentLoaded', function() {
    // 平滑滚动函数
    function smoothScrollTo(targetId) {
        const targetElement = document.getElementById(targetId);
        if (targetElement) {
            window.scrollTo({
                top: targetElement.offsetTop - 80, // 减去导航栏高度
                behavior: 'smooth'
            });
        }
    }

    // 为导航链接添加平滑滚动
    document.querySelectorAll('nav a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href').substring(1);
            smoothScrollTo(targetId);
        });
    });

    // 初始化自定义下拉选择器
    const customSelects = document.querySelectorAll('.custom-select');
    
    customSelects.forEach(select => {
        const selected = select.querySelector('.select-selected');
        const options = select.querySelectorAll('.select-option');
        const hiddenInput = select.querySelector('input[type="hidden"]');
        
        // 点击选中项显示/隐藏下拉菜单
        selected.addEventListener('click', function(e) {
            e.stopPropagation();
            const items = this.nextElementSibling;
            items.classList.toggle('show');
        });

        // 点击选项更新选中值
        options.forEach(option => {
            option.addEventListener('click', function() {
                const value = this.getAttribute('data-value');
                const icon = this.querySelector('i').cloneNode(true);
                const text = this.textContent.trim();
                
                // 更新选中显示
                selected.innerHTML = '';
                selected.appendChild(icon);
                selected.appendChild(document.createTextNode(text));
                
                // 更新隐藏输入值
                hiddenInput.value = value;
                
                // 关闭下拉菜单
                const items = this.parentElement;
                items.classList.remove('show');
            });
        });
    });

    // 点击页面其他位置关闭所有下拉菜单
    document.addEventListener('click', function() {
        document.querySelectorAll('.select-items').forEach(item => {
            item.classList.remove('show');
        });
    });

    // 合并后的初始化流程
    initializeChart();
    engagementChart.options.plugins.title.display = true;
    engagementChart.options.plugins.title.text = '曝光量与累计互动数关系（示例数据）';
    engagementChart.update();
    resultsSection.style.display = 'block';
    showCompletedStatus(); // 设置初始状态为"预测完成"

    // 初始化示例内容
    const exampleA = `标题："省时又省心！智能扫地机器人，解放双手的科技之选"\n正文：\n\n采用LDS激光导航，精准建图覆盖率提升30%\n\n5200mAh大电池，200㎡户型一次扫完\n\n手机APP远程控制，定制清洁计划\n\n30天无忧退换，2年质保承诺`;
    const exampleB = `标题："把打扫时间留给生活，让温暖重回你的客厅"\n正文：\n\n清晨阳光洒进窗户时，地板已静静准备好迎接你的光脚丫\n\n加班深夜回家，再也不用面对散落的零食碎屑\n\n它记得每个角落的轨迹，就像记得你总爱蜷缩的沙发位置\n\n生活应该装满咖啡香和笑声，而不是扫帚与灰尘`;
    
    versionAInput.value = exampleA;
    versionBInput.value = exampleB;
    versionAInput.dispatchEvent(new Event('input'));
    versionBInput.dispatchEvent(new Event('input'));

    console.log("Script loaded and initialized.");
});

// --- 状态图标控制 ---
function showPredictingStatus() {
    const predictingIcon = document.getElementById('predicting_icon');
    const completedIcon = document.getElementById('completed_icon');
    
    if (predictingIcon) predictingIcon.style.display = 'flex';
    if (completedIcon) completedIcon.style.display = 'none';
}

function showCompletedStatus() {
    const predictingIcon = document.getElementById('predicting_icon');
    const completedIcon = document.getElementById('completed_icon');
    
    if (predictingIcon) predictingIcon.style.display = 'none';
    if (completedIcon) completedIcon.style.display = 'flex';
}

// 修改预测按钮点击事件
predictButton.addEventListener('click', async () => {
    // 移除预测按钮点击时的showPredictingStatus调用
    // 原有代码...
});

// 修改SSE处理函数
function handleStreamDone() {
    console.log("SSE stream finished.");
    showCompletedStatus();
    // 原有代码...
}

function handleStreamError(errorData) {
    console.error('SSE Error message:', errorData.message);
    showCompletedStatus();
    // 原有代码...
}